use utf8;

############################################################################################
#                               Définition de l'onglet Livre                               #
############################################################################################

my $book = $blocnote->add('Livre', -label => 'Livre',);
$book->configure( -background => 'white',);

# Message de retour
my $messageBook = '';

# Mise en place du titre
my $c = $book->Canvas(-width => 500, -height => 1, -background => 'white', -borderwidth => 0)->pack(-pady => 2);
$c->createLine(1,1, 500,1); 
$book->Label ( -text => "Rechercher / Ajouter un Livre", -background => 'white')->pack();
$c = $book->Canvas(-width => 500, -height => 1, -background => 'white', -borderwidth => 0)->pack();
$c->createLine(1,1, 500,1); 

# Définition des champs de recherche
my $field = $book->Frame(-background => 'white')->pack(-anchor => 'n', -pady => 15, -padx => 15);

$field->Label(-text => 'Titre:', -background => 'white')->grid(-row => 0, -column => 0, -sticky => 'w');
my $title = $field->Entry()->grid(-row => 0, -column => 1);

$field->Label( -text => 'Nom de l\'auteur:', -background => 'white', -justify => 'left')->grid(-row => 1, -column => 0, -sticky => 'w');
my $authorName = $field->Entry()->grid(-row => 1, -column => 1);

$field->Label( -text => 'Prénom de l\'auteur:', -background => 'white', -justify => 'left')->grid(-row => 2, -column => 0, -sticky => 'w');
my $authorFirstName = $field->Entry()->grid(-row => 2, -column => 1);

$field->Label( -text => 'Éditeurs:', -background => 'white',)->grid(-row => 3, -column => 0, -sticky => 'w');
my $editor = $field->Entry()->grid(-row => 3, -column => 1);

$field->Label( -text => 'N° ISBN:', -background => 'white',)->grid(-row => 4, -column => 0, -sticky => 'w');
my $number = $field->Entry()->grid(-row => 4, -column => 1);

$field->Label( -text => 'Date d\'achat:', -background => 'white',)->grid(-row => 5, -column => 0, -sticky => 'w');
my $date = $field->Entry()->grid(-row => 5, -column => 1);

$field->Label( -text => 'Prix d\'achat:', -background => 'white',)->grid(-row => 6, -column => 0, -sticky => 'w');
my $price = $field->Entry()->grid(-row => 6, -column => 1);
my $loanable = 2;
$field->Label(-text => 'Empruntable:', -background => 'white')->grid(-row => 7, -column => 0, -sticky => 'w');
$field->Radiobutton(-background => 'white', -activebackground => 'white', -highlightthickness => 0, -variable => \$loanable, -value=>1, -text => "Oui")->grid(-row => 7, -column => 1, -sticky => 'w');
$field->Radiobutton(-background => 'white', -activebackground => 'white', -highlightthickness => 0, -variable => \$loanable, -value=>0, -text => "Non")->grid(-row => 7, -column => 1, -sticky => 'e');

my $buttonFrameBook = $book->Frame(-background => 'white')->pack(-anchor => 'n');

$buttonFrameBook->Button(-text => 'Ajouter',
                     -command => [sub{
            if($title->get ne '' 
               and $authorName->get ne '' 
               and $authorFirstName->get ne '' 
               and $editor->get ne '' 
               and $number->get ne '' 
               and $date->get ne ''
               and $price->get ne '' 
               and $loanable != 2){AddBook();}
            else{ $messageBook = "Pour ajouter un livre merci de renseigner tous les champs.";}}])->grid(-row => 8, -column => 0, -pady => 5, -sticky => 'w', -padx => 7);
$buttonFrameBook->Button(-text => 'Rechercher', -command => [\&SearchBook])->grid(-row => 8, -column => 1, -pady => 5, -sticky => 'w', -padx => 7);
$buttonFrameBook->Button(-text => 'Effacer', -command =>[\&ClearBook,$title, $authorName, $authorFirstName, $editor, $number, $date, $price, \$loanable])->grid(-row => 8, -column => 2, -pady => 5, -sticky => 'w', -padx => 7);

$book->Label(-textvariable => \$messageBook, -background => 'white')->pack();

############################################################################################
#                              Fonctions de gestion des Livres                             #
############################################################################################

# Fonction ajoutant un livre
sub AddBook {
  my $dialog_box = $window->DialogBox(-title => 'Ajout d\'un livre', -buttons => ["OK"], -background => 'white');
  gestion_bd::addBook($title->get, $authorName->get, $authorFirstName->get, $editor->get, $number->get, $date->get, $price->get, $loanable);
  $dialog_box->Label(-text => "Livre ajouté !", -background => 'white')->pack();
  $dialog_box->Show();
}

# Fonction supprimant un livre (ISBN)
sub DeleteBook {
  my $dialog_box = $window->DialogBox(-title  => 'Suppression d\'un livre', -buttons => ["OK"], -background => 'white');
  gestion_bd::deleteBook($_[0]);
  $dialog_box->Label(-text => "Livre supprimé !", -background => 'white')->pack();
  $dialog_box->Show();
}

# Fonction empruntant un livre (ISBN)
sub BorrowBook {
  my $dialog_box = $window->DialogBox(-title  => 'Emprunt d\'un livre', -buttons => ["Emprunter","Annuler"], -background => 'white');
  
  my $fieldDialog_Box = $dialog_box->Frame(-background => 'white')->pack(-anchor => 'n', -pady => 15, -padx => 15);
  $fieldDialog_Box->Label(-text => 'Login:', -background => 'white')->grid(-row => 0, -column => 0, -sticky => 'w');
  my $login = $fieldDialog_Box->Entry()->grid(-row => 0, -column => 1);

  my $reponse = $dialog_box->Show();

  my $id = gestion_bd::getIdSubscriber($login->get);

  if(!defined($id)){
    errorBox("Le login ne correspond à aucun adhérent connu !");
    BorrowBook($_[0]);
  }
  elsif ($reponse eq "Emprunter" and defined($login->get)) {
    gestion_bd::borrowBook($_[0],$id);
    my $dialog_box2 = $window->DialogBox(-title  => 'Emprunt d\'un livre', -buttons => ["OK"], -background => 'white');
    $dialog_box2->Label(-text => "Livre emprunté !", -background => 'white')->pack();
    $dialog_box2->Show();
  }
}

# Fonction affichant les emprunteurs d'un livre donné (ISBN)
sub BorrowerOfBook {
  my $i = 1;
  my $dialog_box = $window->DialogBox(-title => 'Liste des Emprunteurs', -buttons    => ["Modifier", "Supprimer", "Quitter"], -background => 'white');

  $dialog_box->Label(-text => "Nom", -relief =>'groove',)->grid(-row => 0, -column => 1, -sticky => "nsew");
  $dialog_box->Label(-text => "Prénom", -relief =>'groove',)->grid(-row => 0, -column => 2, -sticky => "nsew");
  $dialog_box->Label(-text => "Login", -relief =>'groove',)->grid(-row => 0, -column => 3, -sticky => "nsew");
  $dialog_box->Label(-text => "Filière", -relief =>'groove',)->grid(-row => 0, -column => 4, -sticky => "nsew");
  $dialog_box->Label(-text => "Date d'Emprunt", -relief =>'groove',)->grid(-row => 0, -column => 5, -sticky => "nsew");
  $dialog_box->Label(-text => "Date de Retour", -relief =>'groove',)->grid(-row => 0, -column => 6, -sticky => "nsew");

  my $membersList = gestion_bd::borrowerOfBook($_[0],"");
  my $member;
  foreach my $subscribers (sort {$membersList->{$a}{nomPersonne} cmp $membersList->{$b}{nomPersonne}} keys %{$membersList}) {
    $dialog_box->Radiobutton(-value=>$membersList->{$subscribers}{idAdherent}, -variable=>\$member)->grid(-row => $i, -column => 0,);
    $dialog_box->Label(-text => $membersList->{$subscribers}{nomPersonne}, -background => 'white')->grid(-row => $i, -column => 1,);
    $dialog_box->Label(-text => $membersList->{$subscribers}{prenomPersonne}, -background => 'white')->grid(-row => $i, -column => 2,);
    $dialog_box->Label(-text => $membersList->{$subscribers}{login}, -background => 'white')->grid(-row => $i, -column => 3,);
    $dialog_box->Label(-text => $membersList->{$subscribers}{filiere}, -background => 'white')->grid(-row => $i, -column => 4,);
    $dialog_box->Label(-text => gestion_bd::convertDate($membersList->{$subscribers}{dateEmprunt}), -background => 'white')->grid(-row => $i, -column => 5,);
    $dialog_box->Label(-text => gestion_bd::convertDate($membersList->{$subscribers}{dateRetour}), -background => 'white')->grid(-row => $i, -column => 6,);

    $i = $i + 1;
  }

  my $reponse = $dialog_box->Show();

  if ($reponse eq "Modifier" and defined($member)) {
    ModifyBorrower($_[0],$member);
  }
  elsif ($reponse eq "Supprimer" and defined($member)) {
    DeleteBorrower($_[0],$member);
  }
  elsif ($reponse eq "Modifier" or $reponse eq "Supprimer") {
    errorBox("Veuillez selectionner un adhérent !");
    BorrowerOfBook($_[0]);
  }
}

# Fonction modifiant un emprunt donné (ISBN, idAdherent)
sub ModifyBorrower{
  my $dialog_box = $window->DialogBox(-title => "Modification d'un emprunt", -buttons    => ["Enregistrer", "Annuler"], -background => 'white', -default_button => 'Annuler');
  my $membersList = gestion_bd::borrowerOfBook($_[0],$_[1]);
  my $fieldDialog_Box = $dialog_box->Frame(-background => 'white')->pack(-anchor => 'n', -pady => 15, -padx => 15);

  $fieldDialog_Box->Label( -text => 'Date d\'emprunt:', -background => 'white',)->grid(-row => 1, -column => 0, -sticky => 'w');
  my $dateBorrow = $fieldDialog_Box->Entry(-textvariable => gestion_bd::convertDate($membersList->{$_[1]}{dateEmprunt}))->grid(-row => 1, -column => 1);

  $fieldDialog_Box->Label( -text => 'Date de retour:', -background => 'white',)->grid(-row => 2, -column => 0, -sticky => 'w');
  my $dateReturn = $fieldDialog_Box->Entry(-textvariable => gestion_bd::convertDate($membersList->{$_[1]}{dateRetour}))->grid(-row => 2, -column => 1);

  my $reponse = $dialog_box->Show();
  if ($reponse eq "Enregistrer") {
    gestion_bd::updateBorrower($_[0],$_[1],$dateBorrow->get,$dateReturn->get);
    dialogBox("Information","Modification enregistrée !");
  }
}

# Fonction supprimant un emprunt donné (ISBN, idAdherent)
sub DeleteBorrower{
  my $dialog_box = $window->DialogBox(-title => 'Suppression d\'un emprunt', -buttons => ["OK"], -background => 'white');
  gestion_bd::deleteBorrower($_[0],$_[1]);
  $dialog_box->Label(-text => "Emprunt supprimé !", -background => 'white')->pack();
  $dialog_box->Show();
}

# Fonction modifiant les informations d'un livre donné (ISBN)
sub ModifyBook {
  my $dialog_box = $window->DialogBox(-title => "Modification d'un livre", -buttons    => ["Enregistrer", "Annuler"], -background => 'white', -default_button => 'Annuler');
 
  my $booksList = gestion_bd::searchBook("", "", "", "", $_[0], "", "", 2);
  my $fieldDialog_Box = $dialog_box->Frame(-background => 'white')->pack(-anchor => 'n', -pady => 15, -padx => 15);
  
  $fieldDialog_Box->Label(-text => 'Titre:', -background => 'white')->grid(-row => 0, -column => 0, -sticky => 'w');
  my $title = $fieldDialog_Box->Entry(-textvariable => $booksList->{$_[0]}{titre})->grid(-row => 0, -column => 1);

  $fieldDialog_Box->Label( -text => 'Nom de l\'auteur:', -background => 'white', -justify => 'left')->grid(-row => 1, -column => 0, -sticky => 'w');
  my $authorName = $fieldDialog_Box->Entry(-textvariable => $booksList->{$_[0]}{nomPersonne})->grid(-row => 1, -column => 1);

  $fieldDialog_Box->Label( -text => 'Prénom de l\'auteur:', -background => 'white', -justify => 'left')->grid(-row => 2, -column => 0, -sticky => 'w');
  my $authorFirstName = $fieldDialog_Box->Entry(-textvariable => $booksList->{$_[0]}{prenomPersonne})->grid(-row => 2, -column => 1);

  $fieldDialog_Box->Label( -text => 'Éditeurs:', -background => 'white',)->grid(-row => 3, -column => 0, -sticky => 'w');
  my $editor = $fieldDialog_Box->Entry(-textvariable => $booksList->{$_[0]}{nomEditeur})->grid(-row => 3, -column => 1);

  $fieldDialog_Box->Label( -text => 'Date d\'achat:', -background => 'white',)->grid(-row => 4, -column => 0, -sticky => 'w');
  my $date = $fieldDialog_Box->Entry(-textvariable => gestion_bd::convertDate($booksList->{$_[0]}{dateAchat}))->grid(-row => 4, -column => 1);

  $fieldDialog_Box->Label( -text => 'Prix d\'achat:', -background => 'white',)->grid(-row => 5, -column => 0, -sticky => 'w');
  my $price = $fieldDialog_Box->Entry(-textvariable => $booksList->{$_[0]}{prixAchat})->grid(-row => 5, -column => 1);
  my $loanable = $booksList->{$_[0]}{empruntable};
  $fieldDialog_Box->Label(-text => 'Empruntable:', -background => 'white')->grid(-row => 6, -column => 0, -sticky => 'w');
  $fieldDialog_Box->Radiobutton(-background => 'white', -activebackground => 'white', -highlightthickness => 0, -variable => \$loanable, -value=>1, -text => "Oui")->grid(-row => 6, -column => 1, -sticky => 'w');
  $fieldDialog_Box->Radiobutton(-background => 'white', -activebackground => 'white', -highlightthickness => 0, -variable => \$loanable, -value=>0, -text => "Non")->grid(-row => 6, -column => 1, -sticky => 'e');

  my $reponse = $dialog_box->Show();

  if ($reponse eq "Enregistrer") {
    gestion_bd::updateBook($title->get,$authorName->get,$authorFirstName->get,$editor->get,$booksList->{$_[0]}{ISBN},$date->get,$price->get,$loanable);
    dialogBox("Information","Modification enregistrée !");
  }
}

# Fonction affichant le résultat de la recherche d'un livre
sub SearchBook {
  my $i = 1;
  my $dialog_box = $window->DialogBox(-title => 'Résultat de la recherche', -buttons    => ["Emprunter", "Liste des Emprunteurs", "Modifier", "Supprimer", "Quitter"], -background => 'white');

  $dialog_box->Label(-text => "ISBN", -relief =>'groove',)->grid(-row => 0, -column => 1, -sticky => "nsew");
  $dialog_box->Label(-text => "Titre", -relief =>'groove',)->grid(-row => 0, -column => 2, -sticky => "nsew");
  $dialog_box->Label(-text => "Nom Auteur", -relief =>'groove',)->grid(-row => 0, -column => 3, -sticky => "nsew");
  $dialog_box->Label(-text => "Prenom auteur", -relief =>'groove',)->grid(-row => 0, -column => 4, -sticky => "nsew");
  $dialog_box->Label(-text => "Editeur", -relief =>'groove',)->grid(-row => 0, -column => 5, -sticky => "nsew");
  $dialog_box->Label(-text => "Date d'achat", -relief =>'groove',)->grid(-row => 0, -column => 6, -sticky => "nsew");
  $dialog_box->Label(-text => "Prix d'achat", -relief =>'groove',)->grid(-row => 0, -column => 7, -sticky => "nsew");
  $dialog_box->Label(-text => "Empruntable", -relief =>'groove',)->grid(-row => 0, -column => 8, -sticky => "nsew");

  my $booksList = gestion_bd::searchBook($title->get, $authorName->get, $authorFirstName->get, $editor->get, $number->get, $date->get, $price->get, $loanable);
  my $book;
  foreach my $b (sort {$booksList->{$a}{titre} cmp $booksList->{$b}{titre}} keys %{$booksList}) {
    $dialog_box->Radiobutton(-value=>$booksList->{$b}{ISBN}, -variable=>\$book)->grid(-row => $i, -column => 0,);
    $dialog_box->Label(-text => $booksList->{$b}{ISBN}, -background => 'white')->grid(-row => $i, -column => 1,);
    $dialog_box->Label(-text => $booksList->{$b}{titre}, -background => 'white')->grid(-row => $i, -column => 2,);
    $dialog_box->Label(-text => $booksList->{$b}{nomPersonne}, -background => 'white')->grid(-row => $i, -column => 3,);
    $dialog_box->Label(-text => $booksList->{$b}{prenomPersonne}, -background => 'white')->grid(-row => $i, -column => 4,);
    $dialog_box->Label(-text => $booksList->{$b}{nomEditeur}, -background => 'white')->grid(-row => $i, -column => 5,);
    $dialog_box->Label(-text => gestion_bd::convertDate($booksList->{$b}{dateAchat}), -background => 'white')->grid(-row => $i, -column => 6,);
    $dialog_box->Label(-text => $booksList->{$b}{prixAchat}.'€', -background => 'white')->grid(-row => $i, -column => 7,);
    if($booksList->{$b}{empruntable} == 1){
      $dialog_box->Label(-text => "Oui", -background => 'white')->grid(-row => $i, -column => 8,);
    }
    else{
      $dialog_box->Label(-text => "Non", -background => 'white')->grid(-row => $i, -column => 8,);
    }
    $i = $i + 1;
  }

  my $reponse = $dialog_box->Show();

  if ($reponse eq "Modifier" and defined($book)) {
    ModifyBook($book);
  }
  elsif ($reponse eq "Supprimer" and defined($book)) {
    DeleteBook($book);
  }
  elsif ($reponse eq "Liste des Emprunteurs" and defined($book)) {
    BorrowerOfBook($book);
  }
  elsif ($reponse eq "Emprunter" and defined($book) and $booksList->{$book}{empruntable} == 1) {
    BorrowBook($book);
  }
  elsif (($reponse eq "Emprunter" or $reponse eq "Liste des Emprunteurs")and defined($book) and $booksList->{$book}{empruntable} == 0) {
    errorBox("Le livre n'est pas empruntable !");
    SearchBook();
  }
  elsif ($reponse eq "Modifier" or $reponse eq "Supprimer" or $reponse eq "Emprunter" or $reponse eq "Liste des Emprunteurs") {
    errorBox("Veuillez selectionner un livre !");
    SearchBook();
  }
}